import React, { useRef } from 'react'
import { List, DatePicker, Drawer, Toast, Modal } from 'antd-mobile'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import {
  getProfile,
  updateAvatar,
  updateProfile,
} from '@/store/actions/profile'
import classNames from 'classnames'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router'
const { Item } = List
export default function ProfileEdit() {
  const history = useHistory()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getProfile())
  }, [dispatch])

  const fileRef = useRef(null)
  const profile = useSelector((state) => state.profile.profile)
  const [open, setOpen] = useState({
    visible: false,
    type: '',
  })

  const [openList, setOpenList] = useState({
    visible: false,
    type: '',
  })
  const onFileChange = async (e) => {
    const file = e.target.files[0]
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updateAvatar(fd))
    Toast.success('修改头像成功', 1, null, false)
    onClose()
  }

  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          console.log('拍照')
        },
      },
      {
        title: '选择相册',
        onClick: () => {
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          onCommit('gender', 0)
        },
      },
      {
        title: '女',
        onClick: () => {
          onCommit('gender', 1)
        },
      },
    ],
  }
  const onClose = () => {
    setOpen({
      visible: false,
      type: '',
    })
    setOpenList({
      visible: false,
      type: '',
    })
  }
  const onCommit = async (type, val) => {
    await dispatch(
      updateProfile({
        [type]: val,
      })
    )
    Toast.success('修改成功', 1, null, false)
    onClose()
  }
  const onBirthChange = (e) => {
    onCommit('birthday', dayjs(e).format('YYYY-MM-DD'))
  }
  const logoutFn = () => {
    Modal.alert('温馨提示', '你确定要退出吗', [
      { text: '取消' },
      {
        text: '确定',
        style: { color: '#FC6627' },
        onPress: () => {
          dispatch(logout())
          history.replace('/login')
        },
      },
    ])
  }
  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人信息</NavBar>
        <div className="wrapper">
          <List className="profile-list">
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
              arrow="horizontal"
              onClick={() => {
                setOpenList({
                  visible: true,
                  type: 'photo',
                })
              }}
            >
              头像
            </Item>
            <Item
              extra={profile.name}
              arrow="horizontal"
              onClick={() => {
                setOpen({
                  visible: true,
                  type: 'name',
                })
              }}
            >
              昵称
            </Item>
            <Item
              extra={
                <span
                  className={classNames('intro', profile.intro ? 'normal' : '')}
                >
                  {profile.intro || '未填写'}
                </span>
              }
              arrow="horizontal"
              onClick={() => {
                setOpen({
                  visible: true,
                  type: 'intro',
                })
              }}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              extra={profile.gender === 0 ? '男' : '女'}
              arrow="horizontal"
              onClick={() => {
                setOpenList({
                  visible: true,
                  type: 'gender',
                })
              }}
            >
              性别
            </Item>
            <DatePicker
              mode="date"
              title="选择生日"
              minDate={new Date('1970-01-01')}
              maxDate={new Date()}
              value={new Date(profile.birthday)}
              onChange={onBirthChange}
            >
              <Item arrow="horizontal">生日</Item>
            </DatePicker>
          </List>
        </div>
        <input type="file" ref={fileRef} hidden onChange={onFileChange} />
        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={logoutFn}>
            退出登录
          </button>
        </div>
      </div>

      {/* 全屏表单抽屉 */}
      <Drawer
        position="right"
        className="drawer"
        style={{ minHeight: document.documentElement.clientHeight }}
        children={''}
        open={open.visible}
        sidebar={
          open.visible && (
            <EditInput onCommit={onCommit} onClose={onClose} type={open.type} />
          )
        }
      >
        Click upper-left corner
      </Drawer>

      {/* 全屏表单抽屉 */}
      <Drawer
        position="bottom"
        className="drawer-list"
        children={''}
        open={openList.visible}
        onOpenChange={onClose}
        sidebar={
          openList.visible && (
            <EditList
              config={config}
              onClose={onClose}
              type={openList.type}
            ></EditList>
          )
        }
      >
        Click upper-left corner
      </Drawer>
    </div>
  )
}
